package com.yubest.mqtt.config;

import com.yubest.mqtt.consts.Consts;
import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import java.util.UUID;

/**
 * 生产者配置
 *
 * @Author: hweiyu
 * @Date: 2022/11/11 11:50
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "mqtt.producer")
public class MqttProducerConfig {

    private String clientId;

    private String[] serverURIs;

    private String username;

    private String password;

    private String defaultTopic;

    @Bean
    public MqttPahoClientFactory producerFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setServerURIs(serverURIs);
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = Consts.OUTPUT_CHANNEL)
    public MessageHandler producerHandler() {
        String id = clientId + "_pub_" + UUID.randomUUID();
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(id, producerFactory());
        messageHandler.setAsync(false);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }

    @Bean(name = Consts.OUTPUT_CHANNEL)
    public MessageChannel producerChannel() {
        return new DirectChannel();
    }
}
